﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Obligatorio2013.Clases;
using Obligatorio2013.Logging;

namespace Obligatorio2013.Modelo
{
    public class Sistema
    {

        private UserController userController;
        private CategoryController catController;
        private PriceController priceController;
        private AdsController adsController;


        #region Singleton
        private readonly static Sistema _instance = new Sistema();
        public static Sistema Instance { get { return _instance; } }
        private Sistema()
        {
            init();
        }
        #endregion

        #region initialization
        private void init()
        {
            Log.Instance.Debug("############# Inicializando Aplicacion #############");
            try
            {
                // TODO: Nico aca inicializar todas las listas.  
                this.userController = UserController.Instance;
                this.catController = CategoryController.Instance;
                this.priceController = PriceController.Instance;
                this.adsController = AdsController.Instance;


            }
            catch (Exception e)
            {
                Log.Instance.ErrorException("Error al inicializar la aplicacion:" + e.Message, e);
            }
            Log.Instance.Debug("############# ############# ############# #############");
        }
        #endregion

        #region Login
        public Users login(String user, String pass)
        {
            Users u = userController.login(user, pass);
            if (u != null)
            {
                return u;
            }
            return null;
        }

        #endregion


        #region Users
        public bool validateUserInfo(string name, string lastname, string address, string location, string phone, string email, string user, string password)
        {
            bool up = userController.validateUserPass(user, password);
            bool testMail = userController.validateEmail(email);


            return up && testMail;

        }

        public void saveUser(string name, string lastname, string address, string location, string phone, string email, string user, string password)
        {
            Users u = new Users(name, lastname, address, location, phone, email, user, password, "PUBLICADOR");
            userController.saveUser(u);
        }

        public bool updateUser(string name, string lastname, string address, string location, string phone, 
            string email, string user, string password, string role, bool active, DateTime suspendedUntil)
        {
            //Users old = new Users();
            //old.UserEmail = email;

            Users u = new Users();
            u.UserName = name;
            u.UserLastName = lastname;
            u.UserAddress = address;
            u.UserAddressLocaltion = location;
            u.UserPhone = phone;
            u.UserEmail = email;
            u.User = user;
            u.UserPass = password;
            u.UserRole = role;
            u.UserActive = !active;
            if (active)
            {
                u.UserInactiveUntil = suspendedUntil;
            }

            return userController.updateUsers(u);
        }


        public List<Users> getUsers()
        {
            return userController.UserList;
        }


        public Users getUserById(string mail) { return userController.getUserById(mail); }

        public List<Users> getUsersByStatus(bool all, bool active) { return userController.getUsersByStatus(all, active); }


        #endregion

        #region Categories

        public List<Category> getCategories()
        {
            return catController.CategoryList;
        }

        public bool validateCategoryInfo(string name)
        {
            return catController.validateName(name);
        }

        public void saveCategory(string name, string key)
        {
            List<string> keys = null;
            if (key != null)
            {
                keys = key.Split(';').ToList();
            }
            Category cat = new Category(name, keys);
            catController.saveCategory(cat);
        }


        #endregion

        #region Costs&Prices

        public bool savePrice(double cost, double percent) 
        {

            Price price = new Price();
            price.percent = percent;
            price.basicCost = cost;
            price.premiumCost = cost * (percent / 100) + cost;
            return priceController.savePrice(price);
        }


        public List<Price> getPrices()
        {

            return priceController.PricesList;
        }


        #endregion



        #region ads

        public List<Advertisement> getAds()
        {
            return adsController.AdsList;

        }


        public bool saveAd(string title, string description, string type, string imgName,
            DateTime from, DateTime to, string contact, string phone, double price, string user) 
        {
            Users usr = userController.getUserById(user);

            if (usr != null)
            {
                Advertisement ad = new Advertisement();
                ad.title = title;
                ad.description = description;
                if (type == "Basic")
                {
                    ad.adType = Advertisement.type.Basic;
                }
                else
                {
                    ad.adType = Advertisement.type.Premium;
                }

                ad.image = imgName;
                ad.dateFrom = from;
                ad.dateTo = to;
                ad.mailContact = contact;
                ad.phoneContact = phone;
                if (price == 0)
                {
                    price = adCostCaluclate(title, description, type, from, to);
                }
                ad.price = price;
                ad.publisher = usr;
                ad.suspended = false;


                return true;

            }
            else
            {
                Log.Instance.Error("No se puede guardar un aviso sin usuario. Error al buscar el usuario.");
                return false;
            }        
        }

        public double adCostCaluclate(string title, string description, string type, DateTime from, DateTime to)
        {
            Price p = priceController.getActualPrice();
            if (p != null)
            {
                Advertisement ad = new Advertisement();
                ad.title = title;
                ad.description = description;
                ad.dateFrom = from;
                ad.dateTo = to;
                if (Double.Parse(type)==0)
                {
                    ad.adType = Advertisement.type.Basic;
                }
                else
                {
                    ad.adType = Advertisement.type.Premium;
                }

                adsController.costCalculate(ad, p);
            }
            return 0;
        }



        #endregion


    }
}